<template>
    <div class="page-container">
        <div class="login-container">
            <div class="login-form">
                <div class="notice">
                    <p>注册用户名不能超过5个字符</p>
                </div>
                <form @submit.prevent="handleLogin">
                    <div class="form-group">
                        <label for="UserName">用户名</label>
                        <el-input
                            placeholder="请输入用户名"
                            v-model="UserName"
                            clearable>
                        </el-input>
                    </div>

                    <div class="form-group">
                        <label for="UserEmail">邮箱</label>
                        <div class="email-group">
                            <el-input
                                placeholder="请输入邮箱"
                                v-model="UserEmail"
                                clearable>
                            </el-input>
                            <el-button
                                type="primary"
                                @click="sendVerificationCode"
                                :disabled="codeSending || countdown > 0"
                                class="send-code-btn">
                                {{ countdown > 0 ? `${countdown}秒后重新发送` : '发送验证码' }}
                            </el-button>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="verificationCode">验证码</label>
                        <el-input
                            placeholder="请输入验证码"
                            v-model="verificationCode"
                            clearable>
                        </el-input>
                    </div>

                    <div class="form-group">
                        <label for="UserPassword">密码</label>
                        <el-input
                            placeholder="请输入密码"
                            v-model="UserPassword"
                            show-password
                            clearable>
                        </el-input>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="UserSex">性别</label>
                            <el-select
                                v-model="selectedUserSex"
                                placeholder="请选择性别">
                                <el-option
                                    v-for="(sex, index) in UserSex"
                                    :key="index"
                                    :label="sex"
                                    :value="sex">
                                </el-option>
                            </el-select>
                        </div>

                        <div class="form-group">
                            <label for="UserAge">年龄</label>
                            <el-input
                                placeholder="请输入年龄"
                                v-model="UserAge"
                                type="number"
                                min="1"
                                max="120">
                            </el-input>
                        </div>

                        <div class="form-group">
                            <label for="UserFrom">国家</label>
                            <el-select
                                v-model="selectedUserFrom"
                                placeholder="请选择国家">
                                <el-option
                                    v-for="(from, index) in UserFrom"
                                    :key="index"
                                    :label="from"
                                    :value="from">
                                </el-option>
                            </el-select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>学院</label>
                            <el-select
                                v-model="selectedCollege"
                                placeholder="请选择学院"
                                @change="initMajor"
                                clearable>
                                <el-option
                                    v-for="(dept, index) in college"
                                    :key="index"
                                    :label="dept.dept_name"
                                    :value="dept.dept_id">
                                </el-option>
                            </el-select>
                        </div>

                        <div class="form-group">
                            <label>专业</label>
                            <el-select
                                v-model="selectMajor"
                                placeholder="请选择专业"
                                :disabled="!selectedCollege"
                                clearable>
                                <el-option
                                    v-for="(dept, index) in major"
                                    :key="index"
                                    :label="dept.dept_name"
                                    :value="dept.dept_id">
                                </el-option>
                            </el-select>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button class="register-button" type="submit">注册</button>
                    </div>
                </form>
            </div>
        </div>

        <footer class="page-footer">
            <p>网站作者：dc大魔王</p>
        </footer>
    </div>
</template>

<script>
import { register_Choose_Major, rigister_Choose, register, sendEmail } from "@/api/api";

export default {
    name: 'RegisterPage',
    data() {
        return {
            UserName: '',
            UserEmail: '',
            UserPassword: '',
            verificationCode: '',
            codeSending: false,
            countdown: 0,
            timer: null,
            UserSex: ['男', '女', '不选择'],
            selectedUserSex: '不选择',
            UserAge: '',
            UserFrom: ['中国', '美国', '俄罗斯', '法国', '英国', '不选择'],
            selectedUserFrom: '不选择',
            college: [],
            major: [],
            selectedCollege: '',
            selectMajor: '',
        };
    },
    created() {
        this.initCollege();
    },
    beforeDestroy() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    },
    methods: {
        async initCollege() {
            try {
                const response = await rigister_Choose();
                this.college = response.data.data || [];
            } catch (error) {
                console.error('获取学院信息失败:', error);
                this.$message.error('获取学院信息失败');
            }
        },

        async initMajor() {
            if (!this.selectedCollege) {
                this.major = [];
                this.selectMajor = '';
                return;
            }

            try {
                const response = await register_Choose_Major({
                    params: {
                        parent_id: this.selectedCollege,
                    },
                });
                this.major = response.data.data || [];
            } catch (error) {
                console.error('获取专业信息失败:', error);
                this.$message.error('获取专业信息失败');
            }
        },

        async sendVerificationCode() {
            if (!this.UserEmail) {
                this.$message.error('请输入邮箱');
                return;
            }

            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(this.UserEmail)) {
                this.$message.error('请输入正确的邮箱格式');
                return;
            }

            this.codeSending = true;
            try {
                const response = await sendEmail(this.UserEmail);
                if (response?.data?.message === "成功") {
                    this.$message.success('验证码已发送，请查收邮件');
                    this.startCountdown();
                } else {
                    this.$message.error(response?.data?.message || '验证码发送失败');
                }
            } catch (error) {
                console.error('发送验证码失败:', error);
                this.$message.error('服务器错误，请稍后重试');
            } finally {
                this.codeSending = false;
            }
        },

        startCountdown() {
            this.countdown = 60;
            this.timer = setInterval(() => {
                if (this.countdown <= 0) {
                    clearInterval(this.timer);
                } else {
                    this.countdown--;
                }
            }, 1000);
        },

        async handleLogin() {
            if (!this.validateForm()) return;

            try {
                const response = await register({
                    userName: this.UserName,
                    userEmail: this.UserEmail,
                    userPassWord: this.UserPassword,
                    userSex: this.selectedUserSex,
                    userAge: this.UserAge,
                    userFrom: this.selectedUserFrom,
                    deptId: this.selectMajor || this.selectedCollege,
                    code: this.verificationCode
                });

                if (response?.data?.message === "成功") {
                    this.$message.success('注册成功！');
                    await this.$router.push('/login');
                } else {
                    this.$message.error(response?.data?.message || '注册失败，请重试');
                }
            } catch (error) {
                console.error('注册请求失败:', error);
                this.$message.error('服务器错误，请稍后再试');
            }
        },

        validateForm() {
            if (!this.UserName || this.UserName.length > 5) {
                this.$message.error('用户名不能为空且不超过5个字符');
                return false;
            }

            if (!this.UserEmail) {
                this.$message.error('请输入邮箱');
                return false;
            }

            if (!this.verificationCode) {
                this.$message.error('请输入验证码');
                return false;
            }

            if (!this.UserPassword || this.UserPassword.length < 6) {
                this.$message.error('密码不能少于6位');
                return false;
            }

            return true;
        }
    }
};
</script>

<style lang="scss" scoped>
.page-container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    background-image: url('https://doocassell.oss-cn-shenzhen.aliyuncs.com/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241219204613.png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    padding: 20px;
    box-sizing: border-box;
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.login-container {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}

.login-form {
    width: 100%;
    max-width: 600px;
    background-color: rgba(255, 255, 255, 0.85);
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    padding: 30px;
    backdrop-filter: blur(5px);

    .notice {
        background-color: rgba(214, 230, 133, 0.6);
        color: #000;
        padding: 12px;
        border-radius: 6px;
        margin-bottom: 24px;
        text-align: center;
        font-size: 14px;
    }

    .form-group {
        margin-bottom: 20px;

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
            text-align: left;
        }

        .el-input, .el-select {
            width: 100%;
        }
    }

    .form-row {
        display: flex;
        gap: 15px;
        margin-bottom: 20px;

        .form-group {
            flex: 1;
            margin-bottom: 0;
        }

        @media (max-width: 600px) {
            flex-direction: column;
            gap: 20px;
        }
    }

    .email-group {
        display: flex;
        gap: 10px;

        .el-input {
            flex: 1;
        }

        .send-code-btn {
            white-space: nowrap;
        }
    }

    .form-actions {
        margin-top: 30px;
        text-align: center;
    }
}

.register-button {
    width: 200px;
    height: 48px;
    border-radius: 24px;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
    background: linear-gradient(135deg, #0fd850 0%, #f9f047 100%);
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 4px 12px rgba(15, 216, 80, 0.3);

    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(15, 216, 80, 0.4);
    }

    &:active {
        transform: translateY(0);
    }
}

.page-footer {
    text-align: center;
    padding: 20px;
    color: #fff;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
    margin-top: auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .login-form {
        padding: 20px;
    }

    .register-button {
        width: 100%;
    }
}

@media (max-width: 480px) {
    .page-container {
        padding: 10px;
    }

    .login-form {
        padding: 15px;
    }
}
</style>
